const randomBetween = function(start, end) {
    var f = start + Math.random() * (end - start + 1)
    return Math.floor(f)
}

class Enemy {
    constructor(game) {
        this.game = game
        this.setUp()
    }

    setUp() {
        this.name = 'enemy'
        this.plane = GuaImage.new(this.game, 'enemy')
        this.boomEffect = GuaParticleSystem.new(this.game)

        this.image = this.plane
        this.speed = randomBetween(3, 6)
        this.setPosition(randomBetween(0, config.screen_width), -randomBetween(50, 100))

        this.hp = randomBetween(1, 10)
        this.alive = true
        this.boomed = false
        this.coolDownToDie = config.coolDownToDie
        this.coolDie = this.coolDownToDie

        // 子弹相关
        this.coolDown = 30
        this.cool = 0
    }

    static new(game) {
        var i = new this(game, name)
        return i
    }



    kill() {
        this.hp -= 1
        if (this.hp == 0) {
            this.boomed = true
            this.game.scene.addElement(this.boomEffect) 
        }

        this.plane.y -= 5
    }

    draw() {
        this.game.drawImage(this.plane)

    }

    fire() {
        if (this.cool == 0) {
            var bullet_speed = 10
            var x = this.plane.x + this.plane.w / 2
            var y = this.plane.y
            var b = Bullet.new(this.game, -10)
            b.name = "enemyBullet"
            b.setPosition(x, y)
            this.scene.addElement(b)

            this.cool = this.coolDown
        }
    }
    update() {
        if (this.cool > 0) {
            this.cool--
        }

        this.moveDown()
        if (this.boomed) {
            this.coolDie -= 1
        }
        if (this.coolDie <= 0) {
            this.boomEffect.disapear()
            this.alive = false
        }
        this.fire()
    }

    moveDown() {
        if (this.plane.y > 600) {
            this.setUp()
        }
        this.setPosition(this.plane.x, this.plane.y += this.speed)
    }

    setPosition(x, y) {
        this.plane.setPosition(x, y)
        this.boomEffect.setPosition(x, y)
    }
}